package com.mmx.baseservice.common.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mmx.baseservice.admin.pojo.AdInfo;
import com.mmx.baseservice.admin.service.AdInfoService;
import com.mmx.baseservice.common.mybatisplus.structure.CustomQueryWrapper;
import com.mmx.baseservice.common.security.config.SecurityConfig;
import com.mmx.baseservice.common.security.jwt.JwtUser;
import com.mmx.baseservice.user.pojo.UsInfo;
import com.mmx.baseservice.user.service.UsInfoService;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户验证方法
 *
 * @author 颜泽贤
 * Created on 2017/12/8
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private AdInfoService adInfoService;
    @Resource
    private UsInfoService usInfoService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username.endsWith(SecurityConfig.ROLE_ADMIN)) { //管理员认证
            QueryWrapper<AdInfo> queryWrapper = new CustomQueryWrapper<AdInfo>()
                    .eq(AdInfo.ACCOUNT, username.replace(SecurityConfig.ROLE_ADMIN, ""));
            AdInfo user = adInfoService.getOne(queryWrapper);
            if (user == null) {
                throw new UsernameNotFoundException(String.format("'%s' invalid", username));
            } else {
                request.setAttribute("adId", user.getId());
                request.setAttribute(AdInfo.ROLE_ID, user.getRoleId());
                return new JwtUser(username, user.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(SecurityConfig.ROLE_ADMIN));
            }
        } else if (username.endsWith(SecurityConfig.ROLE_USER)) {
            QueryWrapper<UsInfo> queryWrapper = new CustomQueryWrapper<UsInfo>()
                    .eq(UsInfo.PHONE, username.replace(SecurityConfig.ROLE_USER, ""));
            UsInfo user = usInfoService.getOne(queryWrapper);
            if (user == null) {
                throw new UsernameNotFoundException(String.format("'%s' invalid", username));
            } else {
                request.setAttribute("usId", user.getId());
                return new JwtUser(username, user.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(SecurityConfig.ROLE_USER));
            }
        } else {
            throw new UsernameNotFoundException(String.format("'%s' invalid", username));
        }

    }

}
